/**
 * Copyright � 2012 GestureSoft. ALL RIGHTS RESERVED.
 * This file contains proprietary and GestureSoft CONFIDENTIAL Information.
 * Use, disclosure or reproduction is prohibited.
 * 
 * @fileName Application.as
 * @creationDate Aug 8, 2012
 * @author 
 * @version 1.0
 */
package com.gesturesoft.imultimax.model.utility
{
	
	import com.gesturesoft.imultimax.AppConst;
	import com.gesturesoft.imultimax.model.AppModel;
	import com.gesturesoft.imultimax.model.DataBaseManager;
	import com.gesturesoft.imultimax.model.dbmanager.DBEncryptor;
	import com.gesturesoft.imultimax.model.error.DataBaseError;
	import com.gesturesoft.imultimax.model.interfaces.IDatabaseManager;
	import com.hurlant.crypto.Crypto;
	import com.hurlant.util.Base64;
	import com.hurlant.util.Hex;
	
	import flash.filesystem.File;
	
	import mx.collections.ArrayCollection;
	
	import pl.randori.air.nativeextensions.ios.MailExtension;

	public class Application
	{
		
		public static var appDBVersion:String = 'DB_VERSION_4';
		
		public static function isActivated():Boolean
		{
			
			var activated:Boolean = true;
			var dbManager:IDatabaseManager = new DataBaseManager();
			dbManager.prepareTable("user");
			var resultCollection:ArrayCollection = retrieveHandler("SELECT usr_status FROM IM_USER");
			
			if(resultCollection.length > 0)
			{
				
				if(resultCollection[0].usr_status == "false")
					activated = false;
				
			}
			else
			{
				
				activated = false;
				
			}
			
			return activated;
			
		}
		
		public static function checkLock():Boolean
		{
			
			var locked:Boolean = true;
			var dbManager:IDatabaseManager = new DataBaseManager();
			//dbManager.prepareTable("user");
			var resultCollection:ArrayCollection = retrieveHandler("SELECT usr_locked FROM IM_USER");
			
			if(resultCollection.length > 0)
			{
				
				if(resultCollection[0].usr_locked == "yes")
					locked = true;
				else
					locked = false;
				
			}
			else
			{
				
				locked = false;
				
			}
			
			return locked;
			
		}
		
		public static function backgroundImage():String
		{
			
			var imgPath:String = null; 
			var startUpCompany:String = Companies.getStartUpCompany();
			var dbManager:IDatabaseManager;
			var query:String;
			var arrCol:ArrayCollection;
			var defaultAssetDetail:Object;
			var formattedActiveThemeDetails:Array;
			var activeThemeImage:String;
			
			formattedActiveThemeDetails = getFormattedActiveThemeDetails();
			
			if( formattedActiveThemeDetails )
			{
				
				if( startUpCompany!=null )
				{
					
					dbManager = new DataBaseManager();
					query = "SELECT * FROM IM_ASSETS WHERE as_company='"+ startUpCompany+"' AND as_type='background'";
					arrCol = retrieveHandler(query);
					if(arrCol.length > 0)
					{
						
						defaultAssetDetail = arrCol[0];
						
						/*if(defaultAssetDetail.as_active_table_propery != null || defaultAssetDetail.as_active_table_propery!="")
						{*/
							
							activeThemeImage = formattedActiveThemeDetails[defaultAssetDetail.as_active_table_propery]["values"];
							if( File.applicationStorageDirectory.resolvePath("backgroundImg.png").exists )
							{
								
								imgPath =  "backgroundImg.png";
								
							}
							else
							{
								
								imgPath = startUpCompany+"/"+defaultAssetDetail.as_value;
								
							}
							
						//}
						//_activeThemeDetails[item.as_active_table_propery][item.values];
						//imgPath =  startUpCompany+"/"+arrCol[0].as_value;
					}
					else
					{
						imgPath = null;
					}
						
					
				}
				
			}
			else
			{
				
				if( startUpCompany!=null )
				{
					
					dbManager = new DataBaseManager();
					query = "SELECT as_value FROM IM_ASSETS WHERE as_company='"+ startUpCompany+"' AND as_type='background'";
					arrCol = retrieveHandler(query);
					if(arrCol.length > 0)
						imgPath =  startUpCompany+"/"+arrCol[0].as_value;
					else
						imgPath = null;
					
				}
				
			}
			
			
			
			return imgPath;
			
		}
		
		private static function getFormattedActiveThemeDetails():Array
		{
			
			var formattedActiveThemeDetails:Array;
			var query:String;
			
			query = "SELECT * FROM IM_THEME_DETAILS WHERE td_id IN (SELECT th_id FROM IM_THEMES WHERE th_active='true')";
			var arrThemes:ArrayCollection = retrieveHandler( query );
			
			if( arrThemes.length > 0 )
			{
				
				formattedActiveThemeDetails = formatActiveThemeDetails( arrThemes );
				
			}
			
			return formattedActiveThemeDetails;
			
		}
		
		private static function formatActiveThemeDetails(arrThemes:ArrayCollection):Array
		{
			
			var formattedActiveThemeDetails:Array = new Array();
			
			formattedActiveThemeDetails = new Array();
			
			for each( var item:Object in arrThemes )
			{
				
				var obj:Object = new Object;
				
				obj.gradient1  = item.gradient1;
				obj.gradient2  = item.gradient2;
				obj.stroke     = item.stroke;
				obj.values	   = item.value;
				obj.color      = item.text_color;
				
				formattedActiveThemeDetails[item.property_name] = obj;
				
			}
			
			return formattedActiveThemeDetails;
			
		}
		
		/**
		 * @param Return true if the application runs first time
		 */ 
		public static function isFirstTime():Boolean
		{
			
			var dbManager:IDatabaseManager = new DataBaseManager();
			dbManager.prepareTable("style_main");
			var styleMain:ArrayCollection =retrieveHandler("SELECT * FROM IM_STYLE_MAIN");
			if(styleMain.length > 0)
				return false;
			else
				return true;
			
			/*var dbManager:IDatabaseManager = new DataBaseManager();
			dbManager.prepareTable("currencies");
			var styleMain:ArrayCollection = dbManager.getData("SELECT * FROM currencies");
			if(styleMain.length > 0)
				return false;
			else
				return true;*/
			
		}
		
		/**
		 * @Return whether user is registered via sms
		 */ 
		public static function isRegisteredViaSMS():Boolean
		{
			
			var registeredViaSMS:Boolean = false;
			var arrResult:ArrayCollection;
			var iDataBaseManger:IDatabaseManager = new DataBaseManager();
			var query:String = "SELECT usr_email FROM IM_USER";
			
			try
			{
				
				arrResult = iDataBaseManger.getData(query);
				if(arrResult.length > 0)
				{
					if(arrResult[0].usr_email == null || arrResult[0].usr_email == "")
					{
						registeredViaSMS = true;
					}
				}
				else
				{
					trace("No user details");
				}
				
			} 
			catch(error:Error) 
			{
				
				trace("Activation:isRegisteredViaSMS()");
				
			}
			
			return registeredViaSMS;
			
		}
		
		public static function checkActivationCodeViaSMS(val:String):Boolean
		{
			
			var isActivationCodeValid:Boolean = false;
			var dbManager:IDatabaseManager = new DataBaseManager();
			var arrUser:ArrayCollection = retrieveHandler("SELECT usr_pin_number FROM IM_USER");
			
			if( arrUser.length > 0 )
			{
				if(arrUser[0].usr_pin_number == val)
				{
					isActivationCodeValid = true;
				}
			}
			
			return isActivationCodeValid;
			
		}
		
		/**
		 * Check if register code matches with db values
		 * 
		 * Matching did by combining pin code in db and udid
		 * and compare with the one user enetered
		 * 
		 * @Return true if activation code matches
		 */ 
		public function checkActivationCode(userEnteredCode:String):Boolean
		{
			
			var codeReturn:Boolean = false;
			var clientCode:String;
			var extension:MailExtension = AppModel.getInstance().extension; 
			var udid:String = "";
			if(AppModel.getInstance().targetPlatform == AppConst.IPHONE)
				udid = extension.getUDID();
			else
				udid = "123456";
			
			if(userEnteredCode != null)
			{
				
				var dbManager:IDatabaseManager = new DataBaseManager();
				
				var arrUser:ArrayCollection = retrieveHandler("SELECT usr_pin_number, usr_activation_rqst_time FROM IM_USER");
				
				var pinNumber:String = arrUser[0].usr_pin_number;
				var activationRequestTime:String = arrUser[0].usr_activation_rqst_time;
				var userEnteredCodeDecrypted:String;
				
				if(arrUser.length > 0)
				{
					
					try
					{
						
						userEnteredCodeDecrypted = DBEncryptor.decrypt(userEnteredCode);
						
					} 
					catch(error:Error) 
					{
						
						throw error;
						
					}
					
					
					if( userEnteredCodeDecrypted == pinNumber+"-"+udid+"-"+activationRequestTime )
					{
						
						codeReturn = true;
						
						//Activation code matches so nullify the activation time(used for unique activation)
						dbManager.execute("UPDATE IM_USER SET usr_activation_rqst_time=''");
						
					}
					
					trace(clientCode);
					
					trace(userEnteredCode);
					
				}
				
			}
			
			return codeReturn;
			
		}
		
		private static function retrieveHandler(val:String):ArrayCollection
		{
			
			var result:ArrayCollection;
			
			var _iDBManager:IDatabaseManager = new DataBaseManager();
			try
			{
				
				result = ArrayCollection(_iDBManager.getData(val));
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("Application-retrieveHandler() : Database Read error");
				throw error;
				
			}
			
			return result;
			
		}
		
		public function insertLocation(longitude:String,latitude:String,distance:String):void
		{
			
			var _iDBManager:IDatabaseManager = new DataBaseManager();
			try
			{
				
				//_iDBManager.prepareTable("locationtable");
				_iDBManager.insertValues("INSERT INTO IM_LOCATION ( loc_longitude, loc_latitude, loc_distance) " + 
					"VALUES('"+ longitude +"','" + latitude +"','" + distance +"')");
				
			} 
			catch(error:DataBaseError) 
			{
				
				trace("Application-retrieveHandler() : Database Read error");
				throw error;
				
			}
			
		}
		
		/**
		 * @Param activity action performed by the user
		 * Insert action performed by the user to local database
		 */ 
		public static function insertActivity(activity:String, action:String, result:String):void
		{
			
			var iDataBaseManager:IDatabaseManager = new DataBaseManager();
			
			try
			{
				
				iDataBaseManager.execute("INSERT INTO IM_ACTIVITIES (act_activity, act_result, act_action) values ('"+activity+"','"+result+"', '"+action+"')");
				
			} 
			catch(error:DataBaseError) 
			{
				
				throw(error);
				
			}
			
		}
		
	}
	
}